package com.team.order.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

public class VerificationCodeUtil {

    /**
     * 生成随机核销码
     *
     * @param length 核销码长度
     * @return 随机核销码
     */
    public static String generateVerificationCode(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < length; i++) {
            code.append(characters.charAt(random.nextInt(characters.length())));
        }
        return code.toString();
    }

    /**
     * 生成核销码的二维码图片
     *
     * @param code   核销码
     * @param width  图片宽度
     * @param height 图片高度
     * @return MultipartFile类型的二维码图片
     * @throws WriterException ZXing写入异常
     * @throws IOException     IO异常
     */
    public static MultipartFile generateQRCodeImage(String code, int width, int height) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(code, BarcodeFormat.QR_CODE, width, height);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);

        return new MockMultipartFile("qrcode.png", // 文件名
                "qrcode.png", // 原始文件名
                "image/png",  // 内容类型
                outputStream.toByteArray() // 文件字节数组
        );
    }

    /**
     * 生成核销码及其二维码图片（固定250x250像素，核销码长度8位）
     *
     * @return 包含核销码和二维码图片的数组，[0]为核销码(String)，[1]为二维码图片(MultipartFile)
     * @throws WriterException ZXing写入异常
     * @throws IOException     IO异常
     */
    public static Object[] generateCodeAndQRImage() throws WriterException, IOException {
        String code = generateVerificationCode(8); // 生成8位核销码
        MultipartFile qrImage = generateQRCodeImage(code, 250, 250); // 生成250x250的二维码图片
        return new Object[]{code, qrImage};
    }
}
